package com.fxtcn.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.drawable.Drawable;
import android.util.Log;

/**
 * @author： 张勇军
 * @E-Mail: zhangyongjun@roadrover.cn
 * @Date ： 2011-5-19 下午05:40:04
 * @Description 文件下载管理
 */
public class FileUtil {

	private static final String TAG = "FileUtil";

	public static final int CREATE_FILE_PATH_TYPE_INAND = 0; // 网络连接失败

	public static final int CREATE_FILE_PATH_TYPE_CDCARD = 1; // 网络连接失败

	public static final int CMD_CONNECT_FAIL = 55; // 网络连接失败

	/**
	 * 判断SDCard 是否准备就绪
	 * 
	 * @return
	 */
	public static boolean isSDCardReady() {
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 创建目录
	 * 
	 * @param dirName
	 * @return
	 * @throws IOException
	 */
	public static File createSDDir(String dirName) throws IOException {
		File dir = new File(dirName);// Constants.SDCARD_PATH + dirName
		if (!dir.exists()) {
			Log.d(TAG, "createSDDir>>>>>>>>>>>" + dirName);
			dir.mkdirs();
		}
		return dir;
	}

	/**
	 * 创建文件
	 * 
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static File createSDFile(String fileName) throws IOException {
		File file = new File(fileName);
		if (!file.exists()) {
			Log.d(TAG, "createSDFile>>>>>>>>>>>" + fileName);
			file.createNewFile();
		}
		return file;
	}

	public static String getFileName(String fileUrl) {
		String fileEx = "";
		String fileNa = "";
		if (fileUrl != null && fileUrl.trim().length() > 0) {
			fileEx = fileUrl.substring(fileUrl.lastIndexOf(".") + 1, fileUrl.length()).toLowerCase();
			fileNa = fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.lastIndexOf("."));
		}
		return fileNa + "." + fileEx;
	}

	/**
	 * 判断文件是否存在
	 * 
	 * @param fileInfo
	 *            全路径 = 文件路径 + 文件名
	 * @return
	 */
	public static boolean isFileExist(String fileInfo) {
		if (!isSDCardReady())
			return false;
		File file = new File(fileInfo);
		return file.exists();
	}

	/**
	 * 判断文件是否存在
	 * 
	 * @param fileInfo
	 *            全路径 = 文件路径 + 文件名
	 * @return
	 */
	public boolean isFileEmpty(String fileInfo) {
		File file = new File(fileInfo);
		if (file.exists()) {
			return (file.length() <= 0);
		}
		return true;
	}

	public static boolean deleteFile(String filePath) {
		File file = new File(filePath);
		if (file.exists()) {
			return file.delete();
		}
		return false;
	}

	// 清除微博缓存
	public static void deleteCache() {
		File iconFile = new File(Constants.ICON_PATH);
		if (iconFile.exists()) {
			Log.d("deleteIcon", iconFile.getName());
			File[] iconfiles = iconFile.listFiles();
			for (int i = 0; i < iconfiles.length; i++) {
				iconfiles[i].delete();
			}
		}

		File albumsFile = new File(Constants.ALBUMS_PATH);
		if (albumsFile.exists()) {
			Log.d("deleteAlbums", albumsFile.getName());
			File[] albumsfiles = albumsFile.listFiles();
			for (int i = 0; i < albumsfiles.length; i++) {

				albumsfiles[i].delete();
			}
		}

		FileUtil.deleteFile(Constants.INAND_PATH + Constants.CACHE_USERINFO);

		Log.d(TAG, "deletePreUserCache>>>>>>>>>>>>>>>>>>" + Constants.CACHE_USERINFO);

		FileUtil.deleteFile(Constants.INAND_PATH + Constants.CACHE_NEARALBUMS);
		Log.d(TAG, "deletePreUserCache>>>>>>>>>>>>>>>>>>" + Constants.CACHE_NEARALBUMS);

		FileUtil.deleteFile(Constants.INAND_PATH + Constants.CACHE_NEARBLOG);
		Log.d(TAG, "deletePreUserCache>>>>>>>>>>>>>>>>>>" + Constants.CACHE_NEARBLOG);

		FileUtil.deleteFile(Constants.INAND_PATH + Constants.CACHE_MAINBLOG);
		Log.d(TAG, "deletePreUserCache>>>>>>>>>>>>>>>>>>" + Constants.CACHE_MAINBLOG);

		FileUtil.deleteFile(Constants.INAND_PATH + Constants.CACHE_MENTION_ME);
		Log.d(TAG, "deletePreUserCache>>>>>>>>>>>>>>>>>>" + Constants.CACHE_MENTION_ME);
	}

	/**
	 * 向SD card 写入文件
	 * 
	 * @param path
	 * @param fileName
	 * @param is
	 * @return
	 */
	public static File writeFileToSDCard(String path, String fileName, InputStream is) {
		File file = null;
		OutputStream os = null;
		if (path != null && fileName != null && is != null) {
			try {
				createSDDir(path);
				Log.v("TAG", "writeFileToSDCard>>>>>>>>>>>>" + path + "fileName:" + fileName);
				file = createSDFile(path + fileName);
				if (file.exists()) {
					os = new FileOutputStream(file);

					byte buf[] = new byte[128];
					do {
						int numread = is.read(buf);
						if (numread <= 0) {
							break;
						}
						os.write(buf, 0, numread);
					} while (true);
				}

			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (is != null) {
						is.close();
					}
					if (os != null) {
						os.close();
					}

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return file;
	}

	/**
	 * 通过内容 String 向SD card 写入文件
	 * 
	 * @param path
	 * @param fileName
	 * @param is
	 * @return
	 */
	public static void writeFileUseWriter(String path, String fileName, String content) {
		File file = null;
		Writer wt = null;
		try {
			createSDDir(path);
			Log.v("writeFileUseWriter", "path:" + path + "fileName:" + fileName);
			file = createSDFile(path + fileName);
			Log.v("writeFileUseWriter", "path:" + path + "fileName:" + fileName);
			wt = new OutputStreamWriter(new FileOutputStream(file));
			wt.write(content);
			wt.flush();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (wt != null)
				try {
					wt.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

	public static String readFileFromJson(String path, String fileName) {
		File file = null;
		Reader reader = null;
		StringBuffer buffer = new StringBuffer();
		// Log.v("TAG", "readFileFromJson::::::path:" + path + "fileName:"
		// + fileName);
		file = new File(path + fileName);// Constants.SDCARD_PATH + path +
		// fileName
		try {
			if (file.exists()) {
				reader = new InputStreamReader(new FileInputStream(file));
				char[] temp = new char[10];
				int length = 0;
				while ((length = reader.read(temp)) != -1) {
					buffer.append(new String(temp, 0, length));
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (reader != null)
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		// Log.v("TAG", "buffer.toString():" + buffer.toString());
		return buffer.toString();
	}

	/***
	 * 
	 * @param fileName
	 *            输出文件
	 * @param content
	 *            输出内容
	 */
	public static void logCat2File(String fileName, String content) {
		if (!isSDCardReady()) {
			return;
		}
		try {
			File file = new File(fileName);
			if (!file.exists()) {
				Log.d(TAG, "logCat2File>>>>>>>>>>>>>>" + "fileName:" + fileName);
				file.createNewFile();
			}
			FileWriter writer = new FileWriter(fileName, true);
			writer.write(content);
			if (writer != null) {
				writer.close();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 下载网络数据流
	 * 
	 * @param urlStr
	 * @return
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	public InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException, IOException {
		InputStream inputStream = null;
		URL url = new URL(urlStr);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		try {
			inputStream = urlConn.getInputStream();
		} catch (IOException e) {
			return null;
		}
		return inputStream;
	}

	/**
	 * Return code : 0 - Successfully 1 - File exists -1 - Down load fail
	 * 
	 * @param urlStr
	 *            网络全路径，比如： urlStr ="http://www.roadqu.com/data/attachment/201105/19/70f3bd98298592cf7c82001c31e401b3_s.jpg"
	 *            ;
	 * @param path
	 *            本地保持路径，默认在/sdcard/下面， 如果要保持在/sdcard/RoadQu/icon/ 目录下，则 path =
	 *            "AppManager/icon/"
	 * @param fileName
	 *            保持的文件名，比如："icon1"
	 * @param isReplace
	 *            是否取代原来的文件
	 * @return
	 */
	public int downLoadFile(String urlStr, String path, String fileName, boolean isReplace) {
		int returnCode = 0;
		InputStream inputStream = null;
		File result = null;
		FileUtil fileUtil = new FileUtil();
		String fileInfo = Constants.SDCARD_PATH + path + fileName;
		if (fileUtil.isFileExist(fileInfo) && !isFileEmpty(fileInfo)) {
			return 1;
		} else {
			try {
				inputStream = this.getInputStreamFromUrl(urlStr);
				result = fileUtil.writeFileToSDCard(path, fileName, inputStream);
				if (result == null) {
					returnCode = -1;
				}
			} catch (MalformedURLException e) {
				// e.printStackTrace();
				returnCode = -1;
			} catch (IOException e) {
				// e.printStackTrace();
				returnCode = -1;
			} finally {
				try {
					if (inputStream != null) {
						inputStream.close();
					}
					if (returnCode == -1 && result == null) {
						return returnCode;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return returnCode;
		}
	}

	/**
	 * 获取图标
	 * 
	 * @param urlStr
	 *            网络全路径，比如： urlStr ="http://www.roadqu.com/data/attachment/201105/19/70f3bd98298592cf7c82001c31e401b3_s.jpg"
	 *            ;
	 * @param path
	 *            本地保持路径，c path = "AppManager/icon/"
	 * @param fileName
	 *            保持的文件名，比如："icon1" = "icon" + @param softId;
	 * @param isReplace
	 *            是否取代原来的文件
	 * @param softId
	 *            软件的编号
	 */
	public Drawable getDrableIcon(String softName) throws IOException {
		// String filePath = AppManagerConstants.SDCARD_PATH +
		// AppManagerConstants.ICON_PATH + "icon" + softId;
		String filePath = Constants.SDCARD_PATH + Constants.ICON_PATH + softName;
		// if filePath == null, 创建一个默认的图标
		File file = new File(filePath);
		boolean exist = file.exists();
		if (!exist) {
			String pathName = Constants.SDCARD_PATH + Constants.ICON_PATH + Constants.DEFAULT_ICON_NAME;
			return Drawable.createFromPath(pathName);
		}
		return Drawable.createFromPath(filePath);
	}

	// 拷贝某个文件
	public static void doCopyFile(String src, String target) throws IOException {
		File srcFile = new File(src);
		File destFile = new File(target);
		if (!destFile.exists()) {
			destFile.createNewFile();
		}
		if (srcFile.exists()) {
			FileInputStream input = new FileInputStream(srcFile);
			try {
				FileOutputStream output = new FileOutputStream(destFile);
				try {
					byte[] buffer = new byte[4096];
					int n = 0;
					while (-1 != (n = input.read(buffer))) {
						output.write(buffer, 0, n);
					}
				} finally {
					try {
						if (output != null) {
							output.close();
						}
					} catch (IOException ioe) {
					}
				}
			} finally {
				try {
					if (input != null) {
						input.close();
					}
				} catch (IOException ioe) {
				}
			}
		}
	}

}
